<?php


namespace app\api\controller;


use think\Controller;
use think\Db;
use think\Exception;
use app\api\model\Member;

/**
 * API基础控制器
 * Class BaseController
 * @package app\api\controller
 */
class BaseController extends Controller
{
    /**
     * 默认返回格式
     * @var array
     */
    protected $returnData = [
        'code' => 200,
        'msg' => 'success',
        'data' => null
    ];
    
    /**
     * 当前登录用户ID
     * @var int|null
     */
    protected $userId = null;
    
    /**
     * 初始化
     */
    protected function _initialize()
    {
        parent::_initialize();
        
        // 跨域请求支持
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Authorization, Content-Type, Accept');
        
        // OPTIONS请求直接返回
        if (request()->isOptions()) {
            exit;
        }
    }
    
    /**
     * 检查用户Token
     * @return bool
     */
    protected function checkToken()
    {
        // 获取请求中的token
        $token = $this->request->header('token');
        if (empty($token)) {
            $token = $this->request->param('token');
        }
        
        if (empty($token)) {
            $this->renderError('缺少token参数', null, 401);
            return false;
        }
        
        // 从缓存中获取用户ID
        $userId = cache('api_token_' . $token);
        if (empty($userId)) {
            $this->renderError('token无效或已过期', null, 401);
            return false;
        }
        
        // 设置当前用户ID
        $this->userId = $userId;
        return true;
    }
    
    /**
     * 返回成功消息（API专用）
     * @param string $msg
     * @param array|null $data
     * @return \think\response\Json
     */
    protected function renderSuccess($msg = 'success', $data = null)
    {
        return json([
            'code' => 200,
            'msg' => $msg,
            'data' => $data
        ]);
    }
    
    /**
     * 返回错误消息（API专用）
     * @param string $msg
     * @param array|null $data
     * @param int $code
     * @return \think\response\Json
     */
    protected function renderError($msg = 'error', $data = null, $code = 400)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
    
    /**
     * 获取当前登录用户ID
     * @return int|null
     */
    protected function getUserId()
    {
        return $this->userId;
    }
    
    /**
     * 旧版API Token验证方法，保留兼容性
     * @param object $obj
     * @param array $post
     * @return int
     */
    public static function verifyToken($obj, $post)
    {
        if (!$obj->request->isPost()) {
            return -1;
        }

        if (!is_array($post) || count($post) == 0) {
            return -2;
        }

        $user = Db::table('api_user')->where('id', '=', 1)->find();
        $cloudSign = md5($user['appKey'] . '_' . $user['appSecret'] . '_' . $user['token']);
        $nowTime = time();
        $upTime = $user['update_time'];
        
        // 验证token是否有效
        if ($nowTime > $upTime) {
            return -3;
        }
        
        try {
            // 验证sign是否正确
            if ($post['sign'] !== $cloudSign) {
                return -5;
            }
        } catch (Exception $e) {
            return -6;
        }
        
        return 0;
    }
}